package com.tapstitch.scm.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * @author zhenyu.guo
 * @date 2018/10/22.
 */
@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Autowired
    public ApplicationContextHolder(ApplicationContext applicationContext) {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    /**
     * 获取名称为name的bean，自动转为所需类型.
     *
     * @param <T>          需求的bean类型
     * @param name         bean名称
     * @param requiredType 需求的bean类型
     * @return 指定类型的bean
     * @throws BeansException 如果找不到匹配的类型，或是类型不能被转换，或是bean实例化失败
     */
    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 按类型获取bean，自动转为所需类型.
     *
     * @param <T>          需求的bean类型
     * @param requiredType 需求的bean类型
     * @return 指定类型的bean
     * @throws BeansException 如果找不到匹配的类型，或是类型不能被转换，或是bean实例化失败
     */
    public static <T> T getBean(Class<T> requiredType) throws BeansException {
        return applicationContext.getBean(requiredType);
    }

    public static void publishEvent(ApplicationEvent event) {
        applicationContext.publishEvent(event);
    }

}
